﻿using CPPEI.ETL.DataServiceInterface;
using CPPEI.ETL.Infrastructure;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ENT = CPPEI.ETL.Domain.Entities;
using MOD = CPPEI.ETL.Domain.Models;

namespace CPPEI.ETL.Domain.Services
{
    public class DtSerService
    {
        #region invoke data source

        public ListResult<Column> GetDataSourceSchema(Guid serviceId, Guid sourceId, string parameters)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.DtSer> serRep = new EntityRepository<ENT.DtSer>(dbContext);
                EntityRepository<ENT.DtSource> dsRep = new EntityRepository<ENT.DtSource>(dbContext);
                EntityRepository<ENT.DtSerType> stRep = new EntityRepository<ENT.DtSerType>(dbContext);
                EntityRepository<ENT.EDtSourceColumn> dscRep = new EntityRepository<ENT.EDtSourceColumn>(dbContext);
                EntityRepository<ENT.EDtSourceParameter> dspRep = new EntityRepository<ENT.EDtSourceParameter>(dbContext);

                Entities.DtSer eDtSer = serRep.Get(p => p.Id == serviceId);
                Entities.DtSource eDtSource = dsRep.Get(p => p.Id == sourceId);
                Entities.DtSerType eSerType = stRep.Get(p => p.Id == eDtSer.TypeId);
                List<Entities.EDtSourceParameter> eParameters = dspRep.Query(p => p.DtSerId == serviceId && p.DtSourceId == sourceId).OrderBy(p => p.Index).ToList();

                Dictionary<string, object> args = new Dictionary<string,object>();

                if(!string.IsNullOrEmpty(parameters))
                {
                    string[] parameterSegments = parameters.Split(new char[] { ',' });
                    if (parameterSegments.Length % 2 != 0)
                    {
                        return new ListResult<Column>(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
                    }

                    if (eParameters != null && eParameters.Count > 0)
                    {
                        for (int index = 0; index < eParameters.Count; index++)
                        {
                            ENT.EDtSourceParameter eParameter = eParameters[index];

                            string valueString = null;
                            for (int indexSegement = 0; indexSegement < parameterSegments.Length; indexSegement += 2)
                            {
                                if (string.Equals(parameterSegments[indexSegement], eParameter.Name, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    valueString = parameterSegments[indexSegement + 1];
                                    break;
                                }
                            }
                            args.Add(eParameter.Name, TaskRuntime.RTParameter.GetValue(eParameter.DataType, valueString));
                        }
                    }
                }

                IDataServiceProxy proxy = DtSerProxyFactory.Create(eSerType.ProxyAssembly, eSerType.ProxyType);
                DataSourceInfo dataSourceInfo = new DataSourceInfo(eDtSer.Address, eDtSer.NeedAuth, eDtSer.AuthUser, CEncoder.Decode(eDtSer.AuthPassword));//密码解密
                dataSourceInfo.DataSource = eDtSource.Value;
                dataSourceInfo.DataSourceValue = eDtSource.Value;

                if(proxy is IColumnEnumerator)
                {
                   List<TDataSourceColumn> dsColumns =  (proxy as IColumnEnumerator).GetColumns(dataSourceInfo);

                   List<Column> columns = new List<Column>();
                   for (int index = 0; index < dsColumns.Count; index++)
                   {
                       Column column = new Column(dsColumns[index].Name, dsColumns[index].DataType);
                       columns.Add(column);
                   }
                   return new ListResult<Column>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), columns);
                }
                else
                {
                    IData data = proxy.GetData(dataSourceInfo, args);

                    if (data != null)
                    {
                        List<Column> columns = data.GetSchema();
                        return new ListResult<Column>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), columns);
                    }
                    else
                    {
                        return new ListResult<Column>(false, ErrorCode.DtSource_DataIsNull, ErrorCode.String(ErrorCode.DtSource_DataIsNull));
                    }
                }
            }
        }

        #endregion

        #region data service type
        /// <summary>
        /// 获取数据服务类型列表
        /// </summary>
        /// <returns></returns>
        public List<MOD.MDtSerCategory> GetTypeList()
        {
            List<MOD.MDtSerCategory> models = new List<MOD.MDtSerCategory>();

            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.DtSerCategory> cRep = new EntityRepository<ENT.DtSerCategory>(context);
                EntityRepository<ENT.DtSerType> tRep = new EntityRepository<ENT.DtSerType>(context);

                List<ENT.DtSerCategory> categories = cRep.GetList(p => p.IsEnabled == true);
                foreach (var category in categories)
                {
                    MOD.MDtSerCategory model = new MOD.MDtSerCategory();
                    model.Id = category.Id;
                    model.Caption = category.Caption;
                    model.Description = category.Description;
                    model.TypeList = tRep.GetList(p => p.IsEnabled == true && p.CategoryId == category.Id);
                    models.Add(model);
                }

                return models;
            }
        }

        /// <summary>
        /// 获取所有的类型，不按照类别分类
        /// </summary>
        /// <returns></returns>
        public List<Entities.DtSerType> GetDtSerTypeList()
        {
            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.DtSerType> tRep = new EntityRepository<ENT.DtSerType>(context);

                return tRep.GetList(p => p.IsEnabled == true);
            }
        }
        #endregion

        #region folder

        /// <summary>
        /// 获取目录树
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<MOD.MDtSerFolder> GetFolderTree(Guid parentId)
        {
            List<MOD.MDtSerFolder> models = new List<MOD.MDtSerFolder>();

            Stack<MOD.MDtSerFolder> stack = new Stack<MOD.MDtSerFolder>();
            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.DtSerFolder> fRep = new EntityRepository<ENT.DtSerFolder>(context);
                List<ENT.DtSerFolder> roots = fRep.GetList(p => p.ParentId == parentId && p.IsDeleted == false && p.IsEnabled == true);
                foreach (var root in roots)
                {
                    MOD.MDtSerFolder model = new MOD.MDtSerFolder();
                    model.Id = root.Id;
                    model.Code = root.Code;
                    model.Caption = root.Caption;
                    model.IsDeleted = root.IsDeleted;
                    model.IsEnable = root.IsEnabled;
                    models.Add(model);

                    stack.Push(model);
                }

                while(stack.Count>0)
                {
                    MOD.MDtSerFolder model = stack.Pop();
                    List<ENT.DtSerFolder> children = fRep.GetList(p => p.ParentId == model.Id && p.IsDeleted == false && p.IsEnabled == true);
                    foreach (var child in children)
                    {
                        MOD.MDtSerFolder childModel = new MOD.MDtSerFolder();
                        childModel.Id = child.Id;
                        childModel.Code = child.Code;
                        childModel.Caption = child.Caption;
                        childModel.IsDeleted = child.IsDeleted;
                        childModel.IsEnable = child.IsEnabled;
                        model.Children.Add(childModel);

                        stack.Push(childModel);
                    }
                }
            }

            return models;
        }

        /// <summary>
        /// 获取目录树
        /// </summary>
        /// <returns></returns>
        public ServiceResult<ENT.DtSerFolder> CreateFolder(string code, string caption, Guid parentId)
        {
            if (string.IsNullOrEmpty(code)
                || string.IsNullOrEmpty(caption))
            {
                return new ServiceResult<ENT.DtSerFolder>(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter), null);
            }

            List<MOD.MDtSerFolder> models = new List<MOD.MDtSerFolder>();

            Stack<MOD.MDtSerFolder> stack = new Stack<MOD.MDtSerFolder>();
            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.DtSerFolder> fRep = new EntityRepository<ENT.DtSerFolder>(context);
                // check parent folder
                if (parentId ==Guid.Empty || fRep.Get(p => p.Id == parentId) != null)
                {
                    // validate code is unique
                    if(fRep.GetList(p=>p.Code == code).Count == 0)
                    {
                        ENT.DtSerFolder entity = new ENT.DtSerFolder();
                        entity.Id = Guid.NewGuid();
                        entity.Code = code;
                        entity.ParentId = parentId;
                        entity.Caption = caption;
                        entity.IsDeleted = false;
                        entity.IsEnabled = true;
                        fRep.Create(entity);

                        if (context.SaveChanges() > 0)
                        {
                            return new ServiceResult<ENT.DtSerFolder>(true, 1, "", entity);
                        }
                        else
                        {
                            return new ServiceResult<ENT.DtSerFolder>(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError), null);
                        }
                    }
                    else
                    {
                        // code has exist
                        return new ServiceResult<ENT.DtSerFolder>(false, ErrorCode.COM_CodeExist, ErrorCode.String(ErrorCode.COM_CodeExist), null);
                    }
                }
                else
                {
                    // parent folder not exist
                    return new ServiceResult<ENT.DtSerFolder>(false, ErrorCode.COM_ParentNotExist, ErrorCode.String(ErrorCode.COM_ParentNotExist), null);
                }
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ServiceResult DeleteFolder(Guid id)
        {
            if(id == Guid.Empty)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            List<MOD.MDtSerFolder> models = new List<MOD.MDtSerFolder>();

            Stack<MOD.MDtSerFolder> stack = new Stack<MOD.MDtSerFolder>();
            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.DtSerFolder> fRep = new EntityRepository<ENT.DtSerFolder>(context);
                EntityRepository<ENT.DtSer> dsRep = new EntityRepository<ENT.DtSer>(context);

                ENT.DtSerFolder eDtSerFolder = fRep.Get(p => p.Id == id);
                if (eDtSerFolder != null)
                {
                    if(fRep.Count(p=>p.ParentId == id) > 0)
                    {
                        //拥有子目录无法被删除
                        return new ServiceResult(false, ErrorCode.COM_FolderHasChildren, ErrorCode.String(ErrorCode.COM_FolderHasChildren));
                    }

                    if(dsRep.Count(p=>p.FolderId == id) > 0)
                    {
                        return new ServiceResult(false, ErrorCode.COM_FolderHasService, ErrorCode.String(ErrorCode.COM_FolderHasService));
                    }

                    fRep.Delete(eDtSerFolder);
                    if (context.SaveChanges() > 0)
                    {
                        return new ServiceResult(true, 1, "");
                    }
                    else
                    {
                        // code has exist
                        return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                    }
                }
                else
                {
                    // parent folder not exist
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }

        /// <summary>
        /// 更新目录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="code"></param>
        /// <param name="caption"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ServiceResult UpdateFolder(Guid id, string code, string caption, Guid parentId)
        {
            if (id == Guid.Empty
                || string.IsNullOrEmpty(code)
                || string.IsNullOrEmpty(caption))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            if(id == parentId)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            List<MOD.MDtSerFolder> models = new List<MOD.MDtSerFolder>();

            Stack<MOD.MDtSerFolder> stack = new Stack<MOD.MDtSerFolder>();
            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.DtSerFolder> fRep = new EntityRepository<ENT.DtSerFolder>(context);
                ENT.DtSerFolder eDtSerFolder = fRep.Get(p => p.Id == id);
                if (eDtSerFolder != null)
                {
                    if(fRep.Get(p=>p.Id != id && p.Code == code) != null)
                    {
                        return new ServiceResult(false, ErrorCode.COM_CodeExist, ErrorCode.String(ErrorCode.COM_CodeExist));
                    }
                    if (parentId != Guid.Empty && fRep.Get(p => p.Id == parentId) == null)
                    {
                        return new ServiceResult(false, ErrorCode.COM_ParentNotExist, ErrorCode.String(ErrorCode.COM_ParentNotExist));
                    }

                    eDtSerFolder.ParentId = parentId;
                    eDtSerFolder.Code = code;
                    eDtSerFolder.Caption = caption;
                    fRep.Update(eDtSerFolder);
                    if (context.SaveChanges() > 0)
                    {
                        return new ServiceResult(true, 1, "");
                    }
                    else
                    {
                        // code has exist
                        return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                    }
                }
                else
                {
                    // parent folder not exist
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }
        #endregion

        #region data source
        
        /// <summary>
        /// 获取类型符合的数据服务对象
        /// </summary>
        /// <param name="dtSerId"></param>
        /// <param name="dtSerTypeId"></param>
        /// <returns></returns>
        public ServiceResult<Views.VDtSer> GetDtSer(Guid dtSerId, Guid dtSerTypeId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                Views.VDtSer vDtSer = dbContext.Database.SqlQuery<Views.VDtSer>("exec [dbo].[ETL_SP_GetDtService] @dtSerId={0}", dtSerId).SingleOrDefault();
                if (vDtSer != null && vDtSer.TypeId == dtSerTypeId)
                {
                    return new ServiceResult<Views.VDtSer>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), vDtSer);
                }
                else
                {
                    return new ServiceResult<Views.VDtSer>(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }
        

        public ServiceResult<Views.VDtSer> GetDtSer(Guid dtSerId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                Views.VDtSer vDtSer = dbContext.Database.SqlQuery<Views.VDtSer>("exec [dbo].[ETL_SP_GetDtService] @dtSerId={0}", dtSerId).SingleOrDefault();
                if(vDtSer != null)
                {
                    return new ServiceResult<Views.VDtSer>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), vDtSer);
                }
                else
                {
                    return new ServiceResult<Views.VDtSer>(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }

        public PagedList<Views.VDtSer> GetDtSerList(Guid folderId, string filter, int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                if(string.IsNullOrEmpty(filter))
                {
                    EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                    List<Views.VDtSer> list = dbContext.Database.SqlQuery<Views.VDtSer>("exec [dbo].[ETL_SP_GetDtSerPagedList] @folderId={0},@start={1},@limit={2}", folderId, start, limit).ToList();
                    int total = dsRep.Count(p => p.FolderId == folderId);
                    return new PagedList<Views.VDtSer>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, list);
                }
                else
                {
                    EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                    List<Views.VDtSer> list = dbContext.Database.SqlQuery<Views.VDtSer>("exec [dbo].[ETL_SP_SearchVDtSerPagedList] @folderId={0}, @filter={1},@start={2},@limit={3}", folderId, filter, start, limit).ToList();
                    int total = dbContext.Database.SqlQuery<int>("exec [dbo].[ETL_SP_SearchVDtSerTotalCount] @folderId={0}, @filter={1}", folderId, filter).SingleOrDefault();
                    return new PagedList<Views.VDtSer>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, list);
                }
            }
        }

        /// <summary>
        /// 获取数据源详细信息
        /// </summary>
        /// <param name="dtSerId"></param>
        /// <param name="dtSourceId"></param>
        /// <returns></returns>
        public ServiceResult<Views.VDtSourceDetail> GetDtSource(Guid dtSerId, Guid dtSourceId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Views.VDtSourceDetail detail = dbContext.Database.SqlQuery<Views.VDtSourceDetail>("exec [ETL_SP_GetDataSourceDetail] @DtSerId={0},@DtSourceId={1}", dtSerId, dtSourceId).SingleOrDefault();

                if (detail != null)
                {
                    EntityRepository<ENT.EDtSourceColumn> dscRep = new EntityRepository<ENT.EDtSourceColumn>(dbContext);
                    EntityRepository<ENT.EDtSourceParameter> dspRep = new EntityRepository<ENT.EDtSourceParameter>(dbContext);

                    detail.Columns = dscRep.Query(p => p.DtSerId == dtSerId && p.DtSourceId == dtSourceId).OrderBy(p => p.Index).ToList();
                    detail.Parameters = dspRep.Query(p => p.DtSerId == dtSerId && p.DtSourceId == dtSourceId).OrderBy(p => p.Index).ToList();
                    return new ServiceResult<Views.VDtSourceDetail>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), detail);
                }
                return new ServiceResult<Views.VDtSourceDetail>(false, ErrorCode.EntityNotFound, ErrorCode.String(ErrorCode.EntityNotFound));
            }
        }

        public PagedList<Views.VDtSource> GetDtSourceList(Guid dtSerId, string hasTask, int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.DtSource> dsRep = new EntityRepository<ENT.DtSource>(dbContext);
                //List<Views.VDtSource> list = dbContext.Database.SqlQuery<Views.VDtSource>("exec [ETL_SP_GetDataSourcePagedList] @DtSerId={0},@start={1},@limit={2}", dtSerId, start, limit).ToList();
                //int total = dsRep.Count(p => p.DtSerId == dtSerId);
                List<Views.VDtSource> list = dbContext.Database.SqlQuery<Views.VDtSource>("exec [ETL_SP_SearchVDtSourcePagedList] @DtSerId={0}, @HasTask={1}, @start={2},@limit={3}", dtSerId, hasTask, start, limit).ToList();
                 int total = dbContext.Database.SqlQuery<int>("exec [ETL_SP_SearchVDtSourceTotalCount] @DtSerId={0},@HasTask={1}", dtSerId, hasTask).SingleOrDefault();
                return new PagedList<Views.VDtSource>(true, ErrorCode.COM_NoError, string.Empty, start, limit, total, list);
            }
        }

        public ListResult<Entities.EDtSourceParameter> GetDtSourceParameters(Guid dtSerId, Guid dtSourceId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                try
                {
                    EntityRepository<ENT.EDtSourceParameter> dspRep = new EntityRepository<ENT.EDtSourceParameter>(dbContext);
                    List<Entities.EDtSourceParameter> list = dspRep.Query(p => p.DtSourceId == dtSourceId && p.DtSerId == dtSerId).OrderBy(p => p.Index).ToList();

                    return new ListResult<ENT.EDtSourceParameter>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), list);
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("获取数据源dtSer:{0},dtSource:{1}的参数列表出错,ex:{2}", dtSerId, dtSourceId, ex));

                    return new ListResult<ENT.EDtSourceParameter>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        public ServiceResult<Entities.DtSer> CreateDtSer(string userId, Guid folderId, string name, string address, bool needAuth,
            string authUser,
            string authPassword,
            Guid categoryId,
            Guid typeId,
            string description)
        {
            if (string.IsNullOrEmpty(name))
            {
                return new ServiceResult<Entities.DtSer>(true, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            if (string.IsNullOrEmpty(address))
            {
                return new ServiceResult<Entities.DtSer>(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            #region 
            ENT.DtSerType dtSerType = null;

            foreach (var category in CPPEI.ETL.Domain.Cache.DtSerCategoryList)
            {
                if(category.Id == categoryId)
                {
                    foreach (var type in category.TypeList)
                    {
                        if (type.Id == typeId)
                        {
                            dtSerType = type;
                            break;
                        }
                    }
                }
            }
            #endregion

            if (dtSerType == null)
            {
                return new ServiceResult<Entities.DtSer>(false, ErrorCode.DtSerTypeNotFound, ErrorCode.String(ErrorCode.DtSerTypeNotFound));
            }
            else
            {
                IDtSerManager manager = DtSerManagerFactory.Create(dtSerType.ManagerAssembly, dtSerType.ManagerType);
                if (manager != null)
                {
                    using(EtlDbContext dbContext = new EtlDbContext())
                    {
                        EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                        //if (typeId != new Guid("{FBC88932-8500-4D98-B795-FF84AEB002C3}"))
                        //{
                        //    // sqlserver类型的不验证地址是否重复
                        //    if (dsRep.Count(p => p.Address == address&&p.TypeId== typeId) > 0)
                        //    {
                        //        return new ServiceResult<Entities.DtSer>(false, ErrorCode.DtSer_AddressExist, ErrorCode.String(ErrorCode.DtSer_AddressExist));
                        //    }

                        //}
                        //// 所有类型的验证地址是否重复   2016-12-28 邢博
                        //if (dsRep.Count(p => p.Address == address && p.TypeId == typeId) > 0)
                        //{
                        //    return new ServiceResult<Entities.DtSer>(false, ErrorCode.DtSer_AddressExist, ErrorCode.String(ErrorCode.DtSer_AddressExist));
                        //}



                        if (dsRep.Count(p => p.Name == name) > 0)
                        {
                            return new ServiceResult<Entities.DtSer>(false, ErrorCode.DtSer_NameExist, ErrorCode.String(ErrorCode.DtSer_NameExist));
                        }

                        try
                        {
                            ServiceResult<Entities.DtSer> result = manager.CreateDataService(dbContext, userId, folderId, name, address, needAuth, authUser, authPassword, categoryId, typeId, description);
                            if (result.IsSuccess)
                            {
                                dbContext.SaveChanges();
                                    new LogService().Write(DEF.LogLevel.Info, "ETL", string.Format("用户:{0}创建了数据服务:{1},类型为:{2}", userId, name, dtSerType.Caption));
                                    return new ServiceResult<Entities.DtSer>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), result.Data);
                            }
                            else
                            {
                                throw new Exception(result.Message);
                            }
                        }
                        catch(Exception ex)
                        {
                            new LogService().Write(DEF.LogLevel.Error, "ETL",
                                string.Format("用户:{0}创建了数据服务:{1},类型为:{2}发生了错误:{3}", userId, name, dtSerType.Caption, ex.Message));
                            return new ServiceResult<Entities.DtSer>(false, ErrorCode.COM_Exception, ex.Message);
                        }
                    }
                }
                else
                {
                    return new ServiceResult<Entities.DtSer>(false, ErrorCode.DtSerManagerNotFound, ErrorCode.String(ErrorCode.DtSerManagerNotFound));
                }
            }
        }


        public ListResult<TDataSource> EnumerateDataSources(Guid dtServiceId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                EntityRepository<Entities.DtSerType> dstRep = new EntityRepository<ENT.DtSerType>(dbContext);
                Entities.DtSer eDtSer = dsRep.Get(p => p.Id == dtServiceId);
                Entities.DtSerType eDtSerType = dstRep.Get(p => p.Id == eDtSer.TypeId);

                IDataServiceProxy proxy = DtSerProxyFactory.Create(eDtSerType.ProxyAssembly, eDtSerType.ProxyType);
                if (proxy != null && proxy is IDetectable)
                {
                    DataServiceInfo dsInfo = new DataServiceInfo(eDtSer.Address, false, string.Empty, string.Empty);
                    try
                    {
                        List<TDataSource> sources = (proxy as IDetectable).EnumerateSources(dsInfo);
                        return new ListResult<TDataSource>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), sources);
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("从数据服务:{0}获取数据源信息出错,ex:{1}", eDtSer.Address, ex));
                        return new ListResult<TDataSource>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                return new ListResult<TDataSource>(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
            }
        }

        public ListResult<TDataSourceParameter> EnumerateParameters(Guid dtServiceId, string dtSourceValue)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.DtSer> dsRep = new EntityRepository<ENT.DtSer>(dbContext);
                EntityRepository<Entities.DtSerType> dstRep = new EntityRepository<ENT.DtSerType>(dbContext);
                Entities.DtSer eDtSer = dsRep.Get(p => p.Id == dtServiceId);
                Entities.DtSerType eDtSerType = dstRep.Get(p => p.Id == eDtSer.TypeId);

                IDataServiceProxy proxy = DtSerProxyFactory.Create(eDtSerType.ProxyAssembly, eDtSerType.ProxyType);
                if (proxy != null && proxy is IDetectable)
                {
                    DataSourceInfo dsInfo = new DataSourceInfo(eDtSer.Address, false, string.Empty, string.Empty);
                    dsInfo.DataSourceValue = dtSourceValue;
                    try
                    {
                        List<TDataSourceParameter> parameters = (proxy as IDetectable).EnumeratePrameters(dsInfo);
                        return new ListResult<TDataSourceParameter>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), parameters);
                    }
                    catch(Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("从数据服务:{0}获取数据源:{1}的参数信息出错,ex:{2}", eDtSer.Address, dtSourceValue, ex));
                        return new ListResult<TDataSourceParameter>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                return new ListResult<TDataSourceParameter>(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dtSerId"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <param name="parameterSettings">name,type,desc,name1,type1,desc1</param>
        /// <param name="columnSettings">name,type,desc,name1,type1,desc1</param>
        /// <param name="settings">数据源的配置信息（key=value,key=value)</param>
        /// <returns></returns>
        public ServiceResult CreateDtSource(string userId, Guid dtSerId, string name, string value, int type, string parameterSettings, string columnSettings,
            string settings)
        {
            if(string.IsNullOrEmpty(name))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            //string[] columnsSettingArr = columnSettings.Split(new char[] { ',' });
            //if(columnsSettingArr.Length % 3 !=0)
            //{
            //    return new ServiceResult(false, ErrorCode.InvalidColumnSettings, ErrorCode.String(ErrorCode.InvalidColumnSettings));
            //}

            //if (string.IsNullOrEmpty(parameterSettings))
            //{
            //    return new ServiceResult(false, ErrorCode.InvalidParameterSettings, ErrorCode.String(ErrorCode.InvalidParameterSettings));
            //}

            //string[] parameterSettingArr = parameterSettings.Split(new char[] { ',' });
            //if (parameterSettingArr.Length % 3 != 0)
            //{
            //    return new ServiceResult(false, ErrorCode.InvalidParameterSettings, ErrorCode.String(ErrorCode.InvalidParameterSettings));
            //}

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Entities.DtSer eDtSer = new EntityRepository<Entities.DtSer>(dbContext).Get(p => p.Id == dtSerId);

                #region
                ENT.DtSerType dtSerType = null;//GetDtSerType(CPPEI.ETL.Domain.Cache.DtSerCategoryList, opParams.TypeId);

                foreach (var category in CPPEI.ETL.Domain.Cache.DtSerCategoryList)
                {
                    if (category.Id == eDtSer.CategoryId)
                    {
                        foreach (var item in category.TypeList)
                        {
                            if (item.Id == eDtSer.TypeId)
                            {
                                dtSerType = item;
                                break;
                            }
                        }
                    }
                }
                #endregion
                if (dtSerType == null)
                {
                    return new ServiceResult(false, ErrorCode.DtSerTypeNotFound, ErrorCode.String(ErrorCode.DtSerTypeNotFound));
                }

                IDtSerManager manager = DtSerManagerFactory.Create(dtSerType.ManagerAssembly, dtSerType.ManagerType);
                if (manager != null)
                {
                    try
                    {
                        ServiceResult result = manager.CreateDataSource(dbContext, userId, dtSerId, name, value, type, parameterSettings, columnSettings,
                            settings);
                        if (result.IsSuccess)
                        {
                            if (dbContext.SaveChanges() > 0)
                            {
                                return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                            }
                            else
                            {
                                return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                            }
                        }
                        else
                        {
                            return result;
                        }
                    }
                    catch(Exception ex)
                    {
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.DtSerManagerNotFound, ErrorCode.String(ErrorCode.DtSerManagerNotFound));
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dtSerId"></param>
        /// <param name="dtSourceId"></param>
        /// <param name="columnSettings">name,type,description,name,type,description</param>
        /// <returns></returns>
        public ServiceResult UpdateDataSourceColumns(string userId, Guid dtSerId, Guid dtSourceId, string columnSettings)
        {
            if (string.IsNullOrEmpty(columnSettings)
                || dtSerId == Guid.Empty
                || dtSourceId == Guid.Empty)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            string[] segements = columnSettings.Split(new char[] { ',' });
            if(segements.Length % 3 != 0
                || segements.Length / 3 == 0)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.EDtSourceColumn> dscRep = new EntityRepository<ENT.EDtSourceColumn>(dbContext);

                dbContext.Database.ExecuteSqlCommand("exec [ETL_SP_DeleteDtSourceColumns] @dtSerId={0},@dtSourceId={1}", dtSerId, dtSourceId);

                // insert data source columns
                // name,type,description,name,type,description
                for (int index = 0; index < segements.Length; index += 3)
                {
                    ENT.EDtSourceColumn eColumn = new ENT.EDtSourceColumn();
                    eColumn.Id = Guid.NewGuid();
                    eColumn.DataType = segements[index + 1];
                    eColumn.DtSerId = dtSerId;
                    eColumn.DtSourceId = dtSourceId;
                    eColumn.Name = segements[index];
                    eColumn.Description = segements[index + 2];
                    eColumn.Index = index / 3;
                    dscRep.Create(eColumn);
                }
                try
                {
                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                    }
                    else
                    {
                        return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                    }
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据源:{0}的列出错,ex:{1}", dtSourceId, ex));
                    return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        public ServiceResult UpdateDataSourceColumns(string userId, Guid dtSerId, Guid dtSourceId, string dtSrcName, string columnSettings)
        {
            if (string.IsNullOrEmpty(columnSettings)
                || string.IsNullOrEmpty(dtSrcName)
                || dtSerId == Guid.Empty
                || dtSourceId == Guid.Empty)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            string[] segements = columnSettings.Split(new char[] { ',' });
            if (segements.Length % 3 != 0
                || segements.Length / 3 == 0)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Entities.DtSource eDtSrc = dbContext.Set<Entities.DtSource>().SingleOrDefault(p => p.Id == dtSourceId);
                if (eDtSrc == null)
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
                eDtSrc.Name = dtSrcName;
                dbContext.Entry<Entities.DtSource>(eDtSrc).State = System.Data.Entity.EntityState.Modified;

                EntityRepository<ENT.EDtSourceColumn> dscRep = new EntityRepository<ENT.EDtSourceColumn>(dbContext);

                // insert data source columns
                // name,type,description,name,type,description
                for (int index = 0; index < segements.Length; index += 3)
                {
                    ENT.EDtSourceColumn eColumn = new ENT.EDtSourceColumn();
                    eColumn.Id = Guid.NewGuid();
                    eColumn.DataType = segements[index + 1];
                    eColumn.DtSerId = dtSerId;
                    eColumn.DtSourceId = dtSourceId;
                    eColumn.Name = segements[index];
                    eColumn.Description = segements[index + 2];
                    eColumn.Index = index / 3;
                    dscRep.Create(eColumn);
                }
                try
                {
                    dbContext.Database.ExecuteSqlCommand("exec [ETL_SP_DeleteDtSourceColumns] @dtSerId={0},@dtSourceId={1}", dtSerId, dtSourceId);
                    dbContext.SaveChanges();
                    return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据源:{0}的列出错,ex:{1}", dtSourceId, ex));
                    return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dtSerId"></param>
        /// <param name="dtSourceId"></param>
        /// <param name="parameterSettings">name,type,defaultValue,desc,name1,type1,defaultValue,desc1</param>
        /// <returns></returns>
        public ServiceResult UpdateDataSourceParameters(string userId, Guid dtSerId, Guid dtSourceId, string parameterSettings)
        {
            if (string.IsNullOrEmpty(parameterSettings)
                || dtSourceId == Guid.Empty)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            string[] segements = parameterSettings.Split(new char[] { ',' });
            if (segements.Length % 4 != 0
                || segements.Length / 4 == 0)
            {
                return new ServiceResult(false, ErrorCode.DtSource_InvalidParameterSettings, ErrorCode.String(ErrorCode.DtSource_InvalidParameterSettings));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.EDtSourceParameter> dspRep = new EntityRepository<ENT.EDtSourceParameter>(dbContext);

                dbContext.Database.ExecuteSqlCommand("delete ETL_DTSourceParameter where DtSourceId={0}", dtSourceId);

                // insert data source columns
                // name,type,defaultValue,description,name,type,defaultValue,description
                for (int index = 0; index < segements.Length; index += 4)
                {
                    ENT.EDtSourceParameter eParameter = new ENT.EDtSourceParameter();
                    eParameter.Id = Guid.NewGuid();
                    eParameter.DataType = segements[index + 1];
                    eParameter.DtSerId = dtSerId;
                    eParameter.DtSourceId = dtSourceId;
                    eParameter.Name = segements[index];
                    eParameter.Description = segements[index + 3];
                    eParameter.DefaultValue = segements[index + 2];
                    eParameter.Index = index / 3;
                    dspRep.Create(eParameter);
                }
                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                }
            }
        }

        #region

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dtSerId"></param>
        /// <param name="dtSourceId"></param>
        /// <param name="dtSrcName"></param>
        /// <param name="dtSrcValue"></param>
        /// <param name="parameterSettings">name,type,defaultValue,desc,name1,type1,defaultValue,desc1</param>
        /// <param name="columnSettings"></param>
        /// <returns></returns>
        public ServiceResult UpdateDataSourceParamsAndColumns(string userId, Guid dtSerId, 
            Guid dtSourceId, 
            string dtSrcName,
            string dtSrcValue,
            string parameterSettings,
            string columnSettings)
        {
            if (string.IsNullOrEmpty(columnSettings)
                || string.IsNullOrEmpty(dtSrcName)
                || dtSerId == Guid.Empty
                || dtSourceId == Guid.Empty
                || string.IsNullOrEmpty(dtSrcValue))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            string[] segements = columnSettings.Split(new char[] { ',' });
            if (segements.Length % 3 != 0
                || segements.Length / 3 == 0)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            if (string.IsNullOrEmpty(parameterSettings)
                || dtSourceId == Guid.Empty)
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            string[] paramsSegments = parameterSettings.Split(new char[] { ',' });
            if (paramsSegments.Length % 4 != 0
                || paramsSegments.Length / 4 == 0)
            {
                return new ServiceResult(false, ErrorCode.DtSource_InvalidParameterSettings, ErrorCode.String(ErrorCode.DtSource_InvalidParameterSettings));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Entities.DtSource eDtSrc = dbContext.Set<Entities.DtSource>().SingleOrDefault(p => p.Id == dtSourceId);
                if (eDtSrc == null)
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
                eDtSrc.Name = dtSrcName;
                eDtSrc.Value = dtSrcValue;
                dbContext.Entry<Entities.DtSource>(eDtSrc).State = System.Data.Entity.EntityState.Modified;

                EntityRepository<ENT.EDtSourceColumn> dscRep = new EntityRepository<ENT.EDtSourceColumn>(dbContext);

                // insert data source columns
                // name,type,description,name,type,description
                for (int index = 0; index < segements.Length; index += 3)
                {
                    ENT.EDtSourceColumn eColumn = new ENT.EDtSourceColumn();
                    eColumn.Id = Guid.NewGuid();
                    eColumn.DataType = segements[index + 1];
                    eColumn.DtSerId = dtSerId;
                    eColumn.DtSourceId = dtSourceId;
                    eColumn.Name = segements[index];
                    eColumn.Description = segements[index + 2];
                    eColumn.Index = index / 3;
                    dscRep.Create(eColumn);
                }
                EntityRepository<ENT.EDtSourceParameter> dspRep = new EntityRepository<ENT.EDtSourceParameter>(dbContext);

                // insert data source columns
                // name,type,defaultValue,description,name,type,defaultValue,description
                for (int index = 0; index < paramsSegments.Length; index += 4)
                {
                    ENT.EDtSourceParameter eParameter = new ENT.EDtSourceParameter();
                    eParameter.Id = Guid.NewGuid();
                    eParameter.DataType = paramsSegments[index + 1];
                    eParameter.DtSerId = dtSerId;
                    eParameter.DtSourceId = dtSourceId;
                    eParameter.Name = paramsSegments[index];
                    eParameter.Description = paramsSegments[index + 3];
                    eParameter.DefaultValue = paramsSegments[index + 2];
                    eParameter.Index = index / 3;
                    dspRep.Create(eParameter);
                }
                try
                {
                    dbContext.Database.ExecuteSqlCommand("delete ETL_DTSourceParameter where DtSourceId={0}", dtSourceId);
                    dbContext.Database.ExecuteSqlCommand("exec [ETL_SP_DeleteDtSourceColumns] @dtSerId={0},@dtSourceId={1}", dtSerId, dtSourceId);
                    dbContext.SaveChanges();
                    return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据源:{0}的列出错,ex:{1}", dtSourceId, ex));
                    return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        #endregion

        public ServiceResult UpdateTaskCategory(string userId, Guid id,
            string code,
            string name)
        {
            if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(name))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Entities.ETaskCategory category = dbContext.Set<Entities.ETaskCategory>().SingleOrDefault(p => p.Id == id);
                if (category == null)
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
                category.Code = code;
                category.Name = name;
                dbContext.Entry<Entities.ETaskCategory>(category).State = System.Data.Entity.EntityState.Modified;
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, ex.Message);
                }
            }
        }

        /// <summary>
        /// 删除数据服务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dtSerId"></param>
        /// <returns></returns>
        public ServiceResult DeleteDtSer(string userId, Guid dtSerId)
        {
            using (EtlDbContext context = new EtlDbContext())
            {
                EntityRepository<ENT.ETask> tRep = new EntityRepository<ENT.ETask>(context);
                if(tRep.Count(p=>p.DtSerId == dtSerId) > 0)
                {
                    // has task, can't delete dtSer
                    return new ServiceResult(false, ErrorCode.DtSerHasTask, ErrorCode.String(ErrorCode.DtSerHasTask));
                }

                // 检查数据服务中是否有数据源关联了数据表
                EntityRepository<ENT.EDtSourceMapping> dsmRep = new EntityRepository<ENT.EDtSourceMapping>(context);
                if(dsmRep.Count(p=>p.DtSerId == dtSerId) > 0)
                {
                    return new ServiceResult(false, ErrorCode.DtSource_HasMappinged, ErrorCode.String(ErrorCode.DtSource_HasMappinged));
                }

                try
                {
                    // delete dtSer
                    context.Database.ExecuteSqlCommand("exec [ETL_SP_DeleteDtSer] @DtSerId={0}", dtSerId);
                    context.SaveChanges();
                    return new ServiceResult();
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("删除数据服务:{0},出错,ex:{1}", dtSerId, ex));
                    return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        public ServiceResult DeleteDataSource(string userId, Guid dtSerId, Guid dtSourceId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.ETask> tRep = new EntityRepository<ENT.ETask>(dbContext);
                if (tRep.Count(p => p.DtSourceId == dtSourceId) > 0)
                {
                    // has task, can't delete dtSource
                    return new ServiceResult(false, ErrorCode.DtSourceHasTask, ErrorCode.String(ErrorCode.DtSourceHasTask));
                }
                EntityRepository<Entities.DtSource>dsRep = new EntityRepository<ENT.DtSource>(dbContext);
                Entities.DtSource eDtSource = dsRep.Get(p => p.DtSerId == dtSerId && p.Id == dtSourceId);
                if (eDtSource == null)
                {
                    return new ServiceResult(true, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
                else
                {

                    dsRep.Delete(eDtSource);
                    try
                    {
                        dbContext.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("删除数据源出错dtser:{0},source:{1},ex:{2}", dtSerId, dtSourceId, ex));
                        return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                    }
                }
                Guid dtTableId = dbContext.Set<Entities.EDtSourceMapping>().Where(p=>p.DtSerId == dtSerId && p.DtSourceId == dtSourceId).Select(p=>p.DtTableId).SingleOrDefault();
                if(dtTableId!= Guid.Empty)
                {
                    return new DeleteService().DeleteDataTableAndMapping(dbContext, userId, dtSerId, dtSourceId, dtTableId);
                }
                else
                {
                    return new ServiceResult(true, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }
            }
        }

        public ServiceResult SetDtSerEnable(string userId, Guid dtSerId, bool isEnabled)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.DtSer> rep = new EntityRepository<ENT.DtSer>(dbContext);

                ENT.DtSer dtSer = rep.Get(p => p.Id == dtSerId);
                if (dtSer != null && dtSer.IsEnabled != isEnabled)
                {
                    dtSer.IsEnabled = isEnabled;
                    rep.Update(dtSer);

                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
                    }
                    else
                    {
                        return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                }
            }
        }

        public ServiceResult UpdateDtSer(string userId, Guid dtSerId, string name, bool isEnabled)
        {
            if(string.IsNullOrEmpty(name))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.DtSer> rep = new EntityRepository<ENT.DtSer>(dbContext);

                ENT.DtSer dtSer = rep.Get(p => p.Id == dtSerId);
                if (dtSer != null)
                {
                    dtSer.Name = name;
                    dtSer.IsEnabled = isEnabled;
                    rep.Update(dtSer);

                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
                    }
                    else
                    {
                        return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                }
            }
        }

        public ServiceResult UpdateDtSrc(string userId, Guid dtSourceId, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.DtSource> rep = new EntityRepository<ENT.DtSource>(dbContext);

                ENT.DtSource dtSource = rep.Get(p => p.Id == dtSourceId);
                if (dtSource != null)
                {
                    dtSource.Name = name;
                    dtSource.CreatedTime = DateTime.Now;
                    rep.Update(dtSource);

                    try
                    {
                        dbContext.SaveChanges();
                        return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
                    }
                    catch (Exception ex)
                    {
                        return new ServiceResult(false, ErrorCode.COM_DBError, ex.Message);
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                }
            }
        }

        public ServiceResult UpdateDtSource(string userId, Guid dtSourceId, string name, string value)
        {
            if (string.IsNullOrEmpty(name))
            {
                return new ServiceResult(false, ErrorCode.COM_InvalidParameter, ErrorCode.String(ErrorCode.COM_InvalidParameter));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<ENT.DtSource> rep = new EntityRepository<ENT.DtSource>(dbContext);

                ENT.DtSource dtSource = rep.Get(p => p.Id == dtSourceId);
                if (dtSource != null)
                {
                    dtSource.Name = name;
                    dtSource.Value = value;
                    dtSource.CreatedTime = DateTime.Now;
                    rep.Update(dtSource);

                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
                    }
                    else
                    {
                        return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                    }
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, string.Empty);
                }
            }
        }
        #endregion
    }
}
